package com.lu.manage.modular.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.lu.manage.core.base.controller.BaseController;
import com.lu.manage.core.common.exception.SysLogExcepetion;
import com.lu.manage.core.schedue.quartz.schedule.QuartzManage;
import com.lu.manage.core.schedue.quartz.utils.ScheduleJobUtils;
import com.lu.manage.core.tips.ErrorTip;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.DateTimeUtils;
import com.lu.manage.modular.system.model.Task;
import com.lu.manage.modular.system.service.TaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;

/**
 * @Project sKnowledge-Blog
 * @Author: zhanglu
 * @Date: 2019-11-15 10:41:48
 * @Description: 系统任务表 控制器
 */
@Controller
@RequestMapping("/system/task")
public class TaskController extends BaseController {

    private static final String PREFIX = "/modular/system/task";

    @Autowired
    private TaskService taskService;

    @Autowired
    private QuartzManage quartzManage;


/*******************************跳转页面相关*******************************/

    /**
    * 首页
    * @return
    */
    @RequestMapping("")
    public String index(){
        return PREFIX + "/index.html";
    }

    /**
    * 新增
    * @return
    */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return PREFIX + "/add.html";
    }

    /**
    * 修改
    * @return
    */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model) throws SysLogExcepetion {
        Task obj = taskService.getById(id);
        model.addAttribute("obj", obj);
        return PREFIX + "/update.html";
    }

    /**
     * 跳转到表达式构建
     * @param cronExpression
     * @param model
     * @return
     */
    @RequestMapping("/toCron")
    public String toCron(String cronExpression, Model model) {
        model.addAttribute("cronExpression", cronExpression);
        return PREFIX + "/cron.html";
    }

/*******************************操作按钮相关*******************************/

    /**
     * 添加
     */
    @RequestMapping("/add")
    @ResponseBody
    @RequiresPermissions(value = "/system/task/add")
    public Object add(Task task) throws SysLogExcepetion {
        taskService.addObj(task);
        return new SuccessTip();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    @RequiresPermissions(value = "/system/task/update")
    public Object update(Task task) throws SysLogExcepetion {
        taskService.updateObj(task);
        return new SuccessTip();
    }

    /**
     * 删除&批量
     */
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = "/system/task/delete")
    public Object delete(String data) throws SysLogExcepetion {
        taskService.deleteObj(data);
        return new SuccessTip();
    }

    /**
     * 正在执行
     * @param data
     * @return
     */
    @RequestMapping("/runNow")
    @ResponseBody
    public Object runNow(String data) throws SysLogExcepetion {
        Task task = JSONObject.parseObject(data, Task.class);
        try {
            quartzManage.runJobNow(ScheduleJobUtils.entityToData(task));
        } catch (SchedulerException e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
        return SUCCESS_TIP;
    }


    /**
     * 执行表达式
     * @return
     */
    @RequestMapping("/doCronExpression")
    @ResponseBody
    public Object doCronExpression(String cronExpression){
        StringBuffer sbResult = new StringBuffer();
        sbResult.append("[");
        try {
            CronTriggerImpl trigger = new CronTriggerImpl();
            trigger.setCronExpression(cronExpression);
            Date start = trigger.getStartTime();
            for(int i=0;i<5;i++){
                Date next = trigger.getFireTimeAfter(start);
                sbResult.append(", \"").append(DateTimeUtils.formatDate(next,"yyyy-MM-dd HH:mm:ss")).append("\"");
                start = next;
            }
            sbResult.append("]");
            return new SuccessTip(sbResult.replace(sbResult.indexOf(","),sbResult.indexOf(",")+1,""));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new ErrorTip(-1,"cron表达式 有问题");
    }



/*******************************查询数据相关*******************************/

    /**
    * 分页查询
    */
    @RequestMapping("/listPage")
    @ResponseBody
    public Object listPage(@RequestParam Map<String, Object> map) throws SysLogExcepetion {
        return taskService.listPage(map);
    }

    /**
     * 所有任务
     * @return
     */
    @RequestMapping("/getAllJob")
    @ResponseBody
    public Object getAllJob(){
        return new SuccessTip(quartzManage.getAllJob());
    }

    /**
     * 正在运行的任务
     * @return
     */
    @RequestMapping("/getRunningJob")
    @ResponseBody
    public Object getRunningJob(){
        return new SuccessTip(quartzManage.getRunningJob());
    }

}
